import { RobotLabelListProps } from "@/api/apiKey/types/apiKey"
import { DeleteRobotId, getRobotLabelList, getRobotList } from "@/api/cloud"
import { RobotListProps } from "@/api/cloud/types/cloud"
import { CategoryType, ModelFormProps } from "@/components/Create/components/cloudModelCreate.vue"
import debounce from "@/utils/debounce"
import { log } from "console"
import { ElMessage, ElMessageBox } from "element-plus"
import { computed, ref } from "vue"
import { useRouter } from "vue-router"

const PAGE_SIZE = 20
export default function useModel(type?: string) {
  const loading = ref<boolean>(false)
  const immediate = ref<boolean>(false)
  const isScroll = ref<boolean>(false)
  const pagination = ref<{ page: number; pageSize: number; count: number }>({
    page: 1,
    pageSize: 0,
    count: 0
  })
  const robotLabelList = ref<RobotLabelListProps[]>([])
  const router = useRouter()
  const visible = ref<boolean>(false)
  const morePopover = ref()
  const buttonRef = ref()
  const editData = ref<ModelFormProps>()
  const modelList = ref<RobotListProps[]>([])
  const label_id = ref<number>(-1)
  const currentLabel = ref<number>(0)

  // 初始化标签模型
  const initRadio = async () => {
    try {
      const { data } = await getRobotLabelList({ page: pagination.value.page })
      const list = data.list?.sort((a: { id: number }, b: { id: number }) => a.id - b.id)
      list.unshift({ id: 0, label: "全部" })
      robotLabelList.value = list
    } catch (error) {
      console.error(error)
    }
  }

  const initCardModelList = async () => {
    await getRobotList({ page: pagination.value.page, labelId: radio.value }).then((res: any) => {
      console.log(12312)
    })
  }

  // 初始化模型列表
  const initCardModelList = async () => {
    let labelId
    loading.value = true
    try {
      if (type) {
        labelId = 0
      } else {
        labelId = label_id.value > 0 ? label_id.value : robotLabelList.value[0]?.id ?? 0
      }
      // hook函数，只需要接收一个labelId即可
      const { data } = await getRobotList({ page: pagination.value.page, label_id: labelId })
      pagination.value.count = data.count
      // 将上一次的数据做连接
      modelList.value = isScroll.value ? modelList.value.concat(data.list) : data.list
    } catch (error) {
      console.error(error)
    } finally {
      loading.value = false
    }
  }

  // 页数
  const pageCount = computed(() => {
    return Math.ceil(pagination.value.count / PAGE_SIZE)
  })

  // 详情跳转
  const handleToRobotDetails = (item: RobotListProps) => {
    router.push({ name: "IntelligentService", query: { id: item.id } })
  }

  const handleOnTab = debounce((id: number, index: number) => {
    console.log(id)

    if (label_id.value === id) return
    currentLabel.value = index
    label_id.value = id
    isScroll.value = false
    pagination.value.page = 1
    initCardModelList()
  }, 200)

  // 编辑回显
  const handleEditDpData = debounce((item: RobotListProps) => {
    editData.value = {
      avatar: item.avatar,
      nickname: item.nickname,
      info: item.info,
      category: item.category as CategoryType,
      label_id: item.label_id,
      id: item.id,
      // @ts-ignore
      isShowAvatar: true
    }
    visible.value = true
  }, 300)

  const handleClose = (type: string) => {
    visible.value = false
    if (type) {
      initCardModelList()
    }
  }

  // 删除
  const handleDeleteId = debounce(async (id: number) => {
    ElMessageBox.confirm("相关智能体将永久删除，请谨慎操作！是否继续删除？", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(async () => {
        await DeleteRobotId({ id })
        modelList.value = modelList.value.filter((item) => item.id !== id)
        ElMessage({
          type: "success",
          message: "删除成功"
        })
      })
      .catch((error: any) => {
        console.error(error)
      })
  }, 300)

  // 下一页
  const nextPage = () => {
    // console.log('pagination.value', pagination.value)
    if (pagination.value.page >= pageCount.value) return
    immediate.value = true
    isScroll.value = true
    pagination.value.page += 1
    initCardModelList()
  }

  return {
    loading,
    morePopover,
    buttonRef,
    pagination,
    pageCount,
    immediate,
    robotLabelList,
    editData,
    modelList,
    label_id,
    currentLabel,
    visible,
    initRadio,
    handleClose,
    handleEditDpData,
    handleOnTab,
    handleToRobotDetails,
    initCardModelList,
    handleDeleteId,
    nextPage
  }
}
